package com.mach.platform.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.google.common.collect.Maps;
import com.mach.platform.domain.Response;
import com.mach.platform.service.DataFormServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author Administrator
 * @Description: 各种文件，输入输出
 * @Package: com.mach.platform.controller
 * @time 2018/11/9 0009 15:30
 */
@RequestMapping("file")
@RestController
public class FileCtrl {

	@Autowired
	private DataFormServiceImpl dataFormService;


	@Value("${victure}")
	private String victures;

	/**
	 * 查找charts的数据
	 *
	 * @param params
	 * @return
	 */
	@PostMapping("charts")
	public Response loadChartsDatas (@RequestParam Map params) {
		if(victures.equals("true")){
			String type = params.get("dataType").toString();
			Map dbResult = null;
			if ("用能占比".equals(type)) {
				dbResult = dataFormService.loadDevChartsDatas(params);
				String s=params.get("singTime").toString();
				String [] srr=s.split(" ");
				String shi=srr[0];//获取出年

				//TODO
				LinkedList<Object> link = new LinkedList<>();
				String []  strs={"涂装车间","机加车间", "其他耗能", "焊装车间", "总装车间", "树脂车间", "铸造车间", "冲压车间"};
				String []  strs2={"离心机","螺杆机", "冷却泵", "冷干机", "吸干机", "冷却塔"};
				for (int i = 0; i <strs.length ; i++) {
					Map<String,Object> map3 = new LinkedHashMap<>();
					map3.put("name",strs[i]);
					Random r = new Random();
					Integer in =r.nextInt(10000)+1;
					map3.put("value",in);
					link.add(map3);
				}
				LinkedList<Object> link2 = new LinkedList<>();
				for (int i = 0; i <strs2.length ; i++) {
					Map<String,Object> map4 = new LinkedHashMap<>();
					map4.put("name",strs2[i]);
					Random r = new Random();
					Integer in =r.nextInt(10000)+1;
					map4.put("value",in);
					link2.add(map4);
				}

                Map<Object,Object> mkl = new LinkedHashMap<>();
				dbResult.put("data",link);
				dbResult.put("legend",strs);
				dbResult.put("legend1",strs2);
				dbResult.put("data2",link2);
				if(params.get("lidu").toString().equals("%Y-%m")){//选择的是月
					String sg=params.get("inTime").toString();
					String [] srrr=sg.split(" ");
					String shig=srrr[0];//获取出年
					dbResult.put("title",shig+" 用能占比");
				}
				if(params.get("lidu").toString().equals("%Y-%m-%d %H:%i")){//选择的是分
					dbResult.put("title",shi+"   用能占比");
				}
				if(params.get("lidu").toString().equals("%Y-%m-%d %H")) {//选择的是时
					dbResult.put("title",shi+"   用能占比");
				}
				if(params.get("lidu").toString().equals("%Y-%m-%d")) {//选择的是天
					String sb=params.get("inTime").toString();
					dbResult.put("title",sb+"   用能占比");
				}
				return Response.ok(dbResult);
			}
				dbResult = dataFormService.loadDevChartsDatas(params);
				if(params.get("lidu").toString().equals("%Y-%m-%d %H:%i")){//选择的是分
					String s=params.get("singTime").toString();
					String [] srr=s.split(" ");
					String shi=srr[0];//年
					String sl=srr[1];//时分秒
					String [] so=sl.split(":");
					String hour=so[0];//获取出时
					String ys=shi+" "+hour;
					LinkedList<Object> link = new LinkedList<>();
					LinkedList<Object> link2 = new LinkedList<>();
					for(int i=0;i<60;i++){
						if(i<10){
							link.add(ys+" :0"+i);
						}else{
							link.add(ys+" :"+i);
						}
					}
					LinkedList link8 = new LinkedList();
					LinkedList link9 = new LinkedList();
					for(int i=0;i<60;i++){
						Random r = new Random();


						Random r2 = new Random();
						Integer s3=r2.nextInt(1000)+1;
						link9.add(s3);
						Integer s1=r.nextInt(1000)+1;

						Random r1 = new Random();
						Integer s2=r1.nextInt(12)+88;
						link8.add(s2);
						link2.add(s1);
					}
					dbResult.put("wData",link9);
					dbResult.put("zData",link8);
					dbResult.put("xData",link);
					dbResult.put("yData",link2);
					dbResult.put("title",shi+"   分趋势图");
					dbResult.put("unit","m³");
				}
				if(params.get("lidu").toString().equals("%Y-%m-%d %H")){//选择的是时
					String s=params.get("singTime").toString();
					String [] srr=s.split(" ");
					String shi=srr[0];//获取出年
					LinkedList<Object> link = new LinkedList<>();
					LinkedList<Object> link2 = new LinkedList<>();
					for(int i=0;i<24;i++){
						if(i<10){
							link.add(shi+" 0"+i);
						}else{
							link.add(shi+" "+i);
						}
					}
					for(int i=0;i<24;i++){
						Random r = new Random();
						Integer s1=r.nextInt(100000)+1;
						link2.add(s1);
					}
					LinkedList links  =new LinkedList();
					LinkedList link9 = new LinkedList();
					for (int i = 0; i <24 ; i++) {
						Random r = new Random();
						Integer s1=r.nextInt(12)+88;
						Random r2 = new Random();
						Integer s3=r2.nextInt(100000)+1;
						link9.add(s3);
						links.add(s1);
					}
					dbResult.put("wData",link9);
					dbResult.put("zData",links);
					dbResult.put("xData",link);
					dbResult.put("yData",link2);
					dbResult.put("title",shi+"   时趋势图");
					dbResult.put("unit","m³");
				}
				if(params.get("lidu").toString().equals("%Y-%m-%d")){//选择的是天

					String s=params.get("inTime").toString();
					String [] srr=s.split("-");
					String shi=srr[0];//获取出年
                    String yue=srr[1];//获取出月
					String  [] yueStr=yue.split("");
					Calendar c = Calendar.getInstance();
					LinkedList<Object> link = new LinkedList<>();
					int year = Integer.valueOf(shi);
					if(yueStr[0].equals("0")){//选择的是1——9月
						Integer s3=Integer.parseInt(yueStr[1]);
						for (int i=s3-1;i<s3;i++){
							c.set(year, i, 1);
							int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
							for (int x=1;x<=lastDay;x++){
								link.add(shi+"-"+(i+1)+"-"+x);
							}
						}
					}
					if(!yueStr[0].equals("0")){
						String sj=yueStr[0]+yueStr[1];
						Integer kl=Integer.parseInt(sj);
						Integer s3=Integer.parseInt(yueStr[1]);
						for (int i=kl-1;i<kl;i++){
							c.set(year, i, 1);
							int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
							for (int x=1;x<=lastDay;x++){
								link.add(shi+"-"+(i+1)+"-"+x);
							}
						}
					}
					LinkedList<Object> link2 = new LinkedList<>();
					LinkedList link9 = new LinkedList();
					LinkedList link3 = new LinkedList();
					for(int i=0;i<link.size();i++){
						Random r = new Random();
						Random r1 = new Random();
						Integer s1=r.nextInt(100000)+1;
						Integer v=r1.nextInt(12)+88;
						link3.add(v);
						link2.add(s1);
						Random r2 = new Random();
						Integer s3=r2.nextInt(100000)+1;
						link9.add(s3);
					}
					dbResult.put("wData",link9);
					dbResult.put("zData",link3);
					dbResult.put("xData",link);
					dbResult.put("yData",link2);
					dbResult.put("unit","m³");
					dbResult.put("title",s+"    天趋势图");
				}
				if(params.get("lidu").toString().equals("%Y-%m")){//选择的是月
					String s=params.get("inTime").toString();
					String [] srr=s.split(" ");
					String shi=srr[0];//获取出年
					String [] arr={shi+"-01", shi+"-02", shi+"-03", shi+"-04", shi+"-05", shi+"-06", shi+"-07", shi+"-08", shi+"-09",shi+"-10",shi+"-11",shi+"-12"};
					LinkedList<Object> link = new LinkedList<>();
					LinkedList<Object> link2 = new LinkedList<>();
					for (int i = 0; i < arr.length; i++) {
						link.add(arr[i]);
					}
					LinkedList link9 = new LinkedList();
					LinkedList link0 = new LinkedList();
					for(int i=0;i<link.size();i++){
						Random r = new Random();
						Random r1 = new Random();
						Integer s1=r.nextInt(100000)+1;
						Integer s2=r1.nextInt(12)+88;
						link0.add(s2);
						link2.add(s1);
						Random r2 = new Random();
						Integer s3=r2.nextInt(100000)+1;
						link9.add(s3);
					}
					dbResult.put("wData",link9);
					dbResult.put("zData",link0);
					dbResult.put("xData",link);
					dbResult.put("yData",link2);
					dbResult.put("unit","m³");
					dbResult.put("title",shi+"    月趋势图");
				}
			return Response.ok(dbResult);
		}else{
			String type = params.get("dataType").toString();
			Map dbResult = null;
			if ("用能占比".equals(type)) {
				params.put("type", "累积用量汇总");
				dbResult = dataFormService.loadDevChartsDatas2(params);
			} else {
				dbResult = dataFormService.loadDevChartsDatas(params);
			}
			return Response.ok(dbResult);
		}

	}

	/**
	 * 查找charts2的数据
	 *
	 * @param params
	 * @return
	 */
	@PostMapping("charts2")
	public Response loadChartsDatas2 (@RequestParam Map params) {
		if (victures.equals("true")) {
			String type = params.get("dataType").toString();
			Map dbResult = null;
			if ("用能占比".equals(type)) {
				dbResult = dataFormService.loadDevChartsDatas(params);
				String s = params.get("singTime").toString();
				String[] srr = s.split(" ");
				String shi = srr[0];//获取出年
				//TODO
				String[] strs2 = {"离心机", "螺杆机", "冷却泵", "冷干机", "吸干机", "冷却塔"};
				LinkedList<Object> link2 = new LinkedList<>();
				for (int i = 0; i < strs2.length; i++) {
					Map<String, Object> map4 = new LinkedHashMap<>();
					map4.put("name", strs2[i]);
					Random r = new Random();
					Integer in = r.nextInt(10000) + 1;
					map4.put("value", in);
					link2.add(map4);
				}
				Map<Object, Object> mkl = new LinkedHashMap<>();
				dbResult.put("legend", strs2);
				dbResult.put("data", link2);
				if (params.get("lidu").toString().equals("%Y-%m")) {//选择的是月
					String sg = params.get("inTime").toString();
					String[] srrr = sg.split(" ");
					String shig = srrr[0];//获取出年
					dbResult.put("title", shig + " 用能占比");
				}
				if (params.get("lidu").toString().equals("%Y-%m-%d %H:%i")) {//选择的是分
					dbResult.put("title", shi + "   用能占比");
				}
				if (params.get("lidu").toString().equals("%Y-%m-%d %H")) {//选择的是时
					dbResult.put("title", shi + "   用能占比");
				}
				if (params.get("lidu").toString().equals("%Y-%m-%d")) {//选择的是天
					String sb = params.get("inTime").toString();
					dbResult.put("title", sb + "   用能占比");
				}

			}
			return Response.ok(dbResult);
		} else {
			String type = params.get("dataType").toString();
			Map dbResult = null;
			if ("用能占比".equals(type)) {
				params.put("type", "累积用量汇总");
				dbResult = dataFormService.loadDevChartsDatas2(params);
			} else {
				dbResult = dataFormService.loadDevChartsDatas(params);
			}
			return Response.ok(dbResult);
		}

	}




	/**
	 * 报表亲求数据
	 *
	 * @param params
	 * @param response
	 * @throws IOException
	 */
	@PostMapping("form")
	public void getForm (@RequestParam Map params, HttpServletResponse response) throws IOException {
		String type = params.get("type").toString();
		if(victures.equals("true")&&"累积用量汇总".equals(type)){
			this.handleUseGasNum(params, response);
			return;
		}
		if ("累积用量汇总".equals(type)) {
			this.handleUseGasNum(params, response);
			return;
		}
		if(victures.equals("true")){
			TemplateExportParams templateExportParams = returnCorrespondingTemplateExportParams(type);
           //数据库真是数据    List<Map> dbResults = dataFormService.loadDevFormDatas(params);

			List<Map> dbResults = dataFormService.loadDevFormDatas2(params);//虚拟数据

			templateExportParams.setHeadingRows(4);
			//制作excel表
			Map<String, Object> excelMap = Maps.newHashMap();
			excelMap.put("maplist", dbResults);

			//把excel模板和 匹配的数据，放进组装方法中，获取一个新的excel文件
			Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);

			ExcelToHtmlParams params1 = new ExcelToHtmlParams(workbook);
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(ExcelXorHtmlUtil.excelToHtml(params1).getBytes());
			outputStream.close();
		}else{
			TemplateExportParams templateExportParams = returnCorrespondingTemplateExportParams(type);

			List<Map> dbResults = dataFormService.loadDevFormDatas(params);

			templateExportParams.setHeadingRows(4);
			//制作excel表
			Map<String, Object> excelMap = Maps.newHashMap();
			excelMap.put("maplist", dbResults);

			//把excel模板和 匹配的数据，放进组装方法中，获取一个新的excel文件
			Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);

			ExcelToHtmlParams params1 = new ExcelToHtmlParams(workbook);
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(ExcelXorHtmlUtil.excelToHtml(params1).getBytes());
			outputStream.close();
		}






	}

	/**
	 * 处理供气用量的数据
	 *
	 * @param params
	 * @param response
	 */
	public void handleUseGasNum (Map params, HttpServletResponse response) throws IOException {
		String type = params.get("lidu").toString();
		String examTime = params.get("singTime").toString();
		String tableName = dataFormService.pickUpTargetTimeStamp(type, examTime);
		TemplateExportParams templateExportParams = returnCorrespondingTemplateExportParamsPerTime(type);
		List<Map> dbResults = dataFormService.loadDevFormDatasGasUsed2(params);

		templateExportParams.setSheetName(tableName);
		//制作excel表
		Map<String, Object> excelMap = Maps.newHashMap();
		excelMap.put("maplist", dbResults);
		excelMap.put("title", tableName);
		//把excel模板和 匹配的数据，放进组装方法中，获取一个新的excel文件
		Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);

		ExcelToHtmlParams params1 = new ExcelToHtmlParams(workbook);
		OutputStream outputStream = response.getOutputStream();
		outputStream.write(ExcelXorHtmlUtil.excelToHtml(params1).getBytes());
		outputStream.close();

	}

	/**
	 * 对应的下载模块 处理
	 *
	 * @param params
	 * @param response
	 * @throws IOException
	 */
	public void handleUseGasNumDownLoad (Map params, HttpServletResponse response) throws IOException {
		String type = params.get("lidu").toString();
		String examTime = params.get("singTime").toString();
		String tableName = dataFormService.pickUpTargetTimeStamp(type, examTime);
		TemplateExportParams templateExportParams = returnCorrespondingTemplateExportParamsPerTime(type);
		List<Map> dbResults = dataFormService.loadDevFormDatasGasUsed(params);

		templateExportParams.setSheetName(tableName);
		//制作excel表
		Map<String, Object> excelMap = Maps.newHashMap();
		excelMap.put("maplist", dbResults);
		excelMap.put("title", tableName);
		//把excel模板和 匹配的数据，放进组装方法中，获取一个新的excel文件
		Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);

		//导出给前端下载
		String fileName = tableName + "累积用量报表导出数据";
		response.setHeader("Content-Disposition",
				"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
		response.setContentType("application/vnd.ms-excel; charset=UTF-8");

		OutputStream outputStream = response.getOutputStream();
		workbook.write(outputStream);

		outputStream.close();

	}

	/**
	 * 下载内容
	 *
	 * @param params
	 * @param response
	 * @throws IOException
	 */
	@PostMapping("dform")
	public void downForm (@RequestParam Map params, HttpServletResponse response) throws IOException {

		String type = params.get("type").toString();

		if ("累积用量汇总".equals(type)) {
			this.handleUseGasNumDownLoad(params, response);
			return;
		}

		TemplateExportParams templateExportParams = returnCorrespondingTemplateExportParams(type);

		List<Map> dbResults = dataFormService.loadDevFormDatas(params);

		templateExportParams.setHeadingRows(4);
		//制作excel表
		Map<String, Object> excelMap = Maps.newHashMap();
		excelMap.put("maplist", dbResults);

		//把excel模板和 匹配的数据，放进组装方法中，获取一个新的excel文件
		Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);

		//导出给前端下载
		String fileName = params.get("type").toString() + "报表导出数据";
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
		response.setContentType("application/vnd.ms-excel; charset=UTF-8");

		OutputStream outputStream = response.getOutputStream();
		workbook.write(outputStream);

		outputStream.close();

	}

	/**
	 * 返回对应的 模板文件配置
	 *
	 * @param type
	 * @return
	 */
	public TemplateExportParams returnCorrespondingTemplateExportParams (String type) {

		// ClassUtils.getDefaultClassLoader().getResource("/static/cool.xlsx").getPath()
		// 这种方式 在windows下的编辑器可用，但是放到linux上运行jar包，不能用。尝试兼容。把excel文件放到 jar包之外去

		String pathName = "";

		switch (type) {
			case "冷干机":
				pathName = "/excel/cool.xlsx";
				break;
			case "离心机":
				pathName = "/excel/lixin.xlsx";
				break;
			case "螺杆机":
				pathName = "/excel/luoganji.xlsx";
				break;
			case "供气总管":
				pathName = "/excel/zongguan.xlsx";
				break;
			case "末端车间":
				pathName = "/excel/moduan.xlsx";
				break;

			default:

				break;
		}

		return new TemplateExportParams(getPicSavePath() + pathName);
	}

	/**
	 * 供气用量 各时段的 表格格式
	 *
	 * @param type 时间粒度
	 * @return
	 */
	public TemplateExportParams returnCorrespondingTemplateExportParamsPerTime (String type) {

		// ClassUtils.getDefaultClassLoader().getResource("/static/cool.xlsx").getPath()
		// 这种方式 在windows下的编辑器可用，但是放到linux上运行jar包，不能用。尝试兼容。把excel文件放到 jar包之外去

		String pathName = "";

		switch (type) {
			case "%Y-%m-%d %H:%i":
				pathName = "/excel/qminute.xlsx";
				break;
			case "%Y-%m-%d %H":
				pathName = "/excel/qhour.xlsx";
				break;
			case "%Y-%m-%d":
				pathName = "/excel/qday.xlsx";
				break;
			case "%Y-%m":
				pathName = "/excel/qmonth.xlsx";
				break;
			default:

				break;
		}

		return new TemplateExportParams(getPicSavePath() + pathName);
	}

	/**
	 * 获取 jar包所在 目录路径
	 *
	 * @return
	 */
	public String getPicSavePath ( ) {
		ApplicationHome home = new ApplicationHome(getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().getParentFile().getAbsolutePath();
	}

}
